package com.emex.app.web.service;

import com.emex.app.shared.data.Orders;
import com.emex.app.shared.data.OrdersExample;
import com.emex.app.shared.persistance.OrdersMapper;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Sergey Karavaev
 */
@Service
@Transactional
public class OrderService {

    @Autowired
    private OrdersMapper ordersMapper;

    public int deleteOrderPrimaryKey(Integer id) {
        return ordersMapper.deleteByPrimaryKey(id);
    }

    public Orders insertOrder(Orders record) {
        record.setDate(correctDate(record.getDate()));
        ordersMapper.insert(record);
        return record;
    }

    public List<Orders> selectOrderByExample(OrdersExample example) {
        List<Orders> list = ordersMapper.selectByExample(example);
        correctDate(list);
        return list;
    }

    public Orders selectOrderByPrimaryKey(Integer id) {
        Orders res = ordersMapper.selectByPrimaryKey(id);
        res.setDate(correctDate(res.getDate()));
        return res;
    }

    public Orders updateOrderByPrimaryKey(Orders record) {
        record.setDate(correctDate(record.getDate()));
        ordersMapper.updateByPrimaryKey(record);
        return record;
    }

    public List<Orders> getAllClientOrders(Integer clientId) {
        OrdersExample example = new OrdersExample();
        example.createCriteria().andClientIdEqualTo(clientId);
        List<Orders> list = selectOrderByExample(example);
        correctDate(list);
        return list;
    }

    public List<Orders> getAllJuridicalClientOrders(Integer jurClientId) {
        OrdersExample example = new OrdersExample();
        example.createCriteria().andJurClienIdEqualTo(jurClientId);
        List<Orders> list = selectOrderByExample(example);
        correctDate(list);
        return list;
    }

    public List<Orders> getOrdersByDate(Date startDate, Date endDate) {
        OrdersExample example = new OrdersExample();
        example.createCriteria().andDateBetween(correctDate(startDate), correctDate(endDate));
        List<Orders> list = selectOrderByExample(example);
        correctDate(list);
        return list;
    }

    private Date correctDate(Date op) {
        final long hours12 = 4L * 60L * 60L * 1000L;
        Date date = new Date(op.getTime() + hours12);
        return date;
    }

    private void correctDate(List<Orders> list) {
        if (null != list && !list.isEmpty()) {
            for (Orders record : list) {
                record.setDate(correctDate(record.getDate()));
            }
        }
    }
}
